import 'dart:async';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:fake_handwriting/Util.dart';
import 'package:fake_handwriting/generated/l10n.dart';
import 'package:fake_handwriting/http/bean/file_bean.dart';
import 'package:fake_handwriting/http/http.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:image_preview/image_preview.dart';

class OnlineImage extends StatefulWidget {
  const OnlineImage({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => OnlineImagePage();
}

class OnlineImagePage extends State<OnlineImage> {
  List<String> urls = [];

  List<FileBean?> beans = [];

  @override
  void initState() {
    super.initState();
    init();
  }

  @override
  Widget build(BuildContext context) {
    String type = ModalRoute.of(context)?.settings.arguments as String;
    return Scaffold(
      body: SafeArea(
          child: GridView.custom(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                mainAxisSpacing: 2,
                crossAxisSpacing: 2,
              ),
              childrenDelegate: SliverChildBuilderDelegate((context, index) {
                return InkWell(
                  onTap: () {
                    if (type == "choose") {
                      Navigator.pop(context, beans[index]);
                    } else {
                      openImagesPage(
                        Navigator.of(context),
                        imgUrls: urls,
                        index: 0,
                      );
                    }
                  },
                  onLongPress: () async {
                    var res = await showDialog(
                        context: context,
                        builder: (context) => SimpleDialog(
                              title: const Text('选择操作'),
                              children: <Widget>[
                                SimpleDialogOption(
                                  child:Text(S.of(context).delete),
                                  onPressed: () {
                                    Navigator.pop(context,S.of(context).delete);
                                  },
                                ),
                                const Divider(),
                                SimpleDialogOption(
                                  child:Text(S.of(context).saveToLocal),
                                  onPressed: () {
                                    Navigator.pop(context, S.of(context).saveToLocal);
                                  },
                                ),
                              ],
                            ));
                    if (res == S.of(context).saveToLocal) {
                      if(await Util.checkPermission(context)){
                        var response = await Dio().get(urls[index], options: Options(responseType: ResponseType.bytes));
                        await ImageGallerySaver.saveImage(Uint8List.fromList(response.data), quality: 100, name: "${DateTime.now().millisecondsSinceEpoch}");
                        Util.toast("保存完毕");
                      }
                    }
                    if (res == S.of(context).delete) {
                      try {
                        await Http.delete_file("${beans[index]!.id}");
                      } catch (e) {}
                    }
                    await init();
                  },
                  child: Container(
                    decoration: BoxDecoration(
                        image: DecorationImage(
                            image: NetworkImage(urls[index].toString()),
                            fit: BoxFit.cover),
                        border: Border.all(color: Colors.blue)),
                  ),
                );
              }, childCount: urls.length))),
      appBar: AppBar(
        title:Text(S.of(context).myBackground),
      ),
      floatingActionButton: (type == "choose")
          ? Container()
          : FloatingActionButton(
              onPressed: () async {
                FilePickerResult? result =
                    await FilePicker.platform.pickFiles(type: FileType.image, allowCompression: false);
                if (result != null) {
                  Util.showLoading(context);
                  try {
                    await Http.upload(result.files.single.path.toString(),
                        result.files.single.name, "images");
                    Util.toast(S.of(context).uploadSuccessful);
                    Navigator.pop(context);
                    init();
                  } catch (e) {
                    Navigator.pop(context);
                    Util.toast("$e");
                  }
                }
              },
              child: const Icon(Icons.cloud_upload),
            ),
    );
  }

  Future<void> init() async {
    urls = [];
    beans = (await Http.get_files("images"))!;
    for (var element in beans) {
      urls.add(Http.BASE_URL+element!.path.toString());
    }
    setState(() {});
  }
}
